/**
 * Project: lionbule-other
 * 
 * File Created at 2012-4-2
 * $Id$
 * 
 * Copyright 1999-2100 Alibaba.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.poi;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

/**
 * BuildeCatalog.
 * 
 * @author LionBule 2012-4-2 上午10:05:09
 */
public class BuildeCatalog {
    private Sheet      sheet;
    private List<Node> datas;
    private Node       root = new Node();

    public BuildeCatalog(Sheet sheet) {
        this.sheet = sheet;
    }

    /**
     * 默认返回所有节点,包含根节点.
     * 
     * @return
     */
    public List<Node> build() {
        datas = new ArrayList<Node>();
        root.setId(-1);

        datas.add(root);

        for (Row row : sheet) {
            int id = row.getRowNum() + 1;
            if (id == 1) {
                continue;
            }

            Cell hr_pid = row.getCell(4);
            int pid = (int) hr_pid.getNumericCellValue();

            Node node = new Node();
            node.setId(id);
            node.setPid(pid);
            node.setLevel(0);
            datas.add(node);
        }

        findReleation(root, datas);

        buildAllNode(root, sheet);

        return datas;
    }

    void buildAllNode(Node pnode, Sheet sheet) {
        List<Node> list = pnode.getChildNodes();
        for (Node d : list) {
            int id = d.getId();
            Row row = sheet.getRow(id - 1);
            Cell cellName = row.getCell(d.getLevel() - 1);
            String name = cellName.getStringCellValue();
            String code = row.getCell(5).getStringCellValue();
            String desc = row.getCell(6).getStringCellValue();
            d.setName(name);
            d.setCode(code);
            d.setDesc(desc);

            buildAllNode(d, sheet);
        }
    }

    void findReleation(Node pnode, List<Node> datas) {
        int pid = pnode.getId();
        for (Node t : datas) {
            if (t.getPid() == pid) {
                t.setParent(pnode);
                t.setLevel(pnode.getLevel() + 1);
                pnode.addChildNode(t);
                findReleation(t, datas);
            }
        }
    }
}
